package com.yty.system.test;


import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogUtil {

    @Pointcut("execution(* com.yty.demo.service..*.*(..)))")
    public void pointcut() {
    }

    //前置通过
    @Before("pointcut()")
    public static void before(JoinPoint joinPoint) {
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
    }

    //后置通知
    @After("execution(* com.yty.demo.service..*.*(..)) && @annotation(apiOperation)")
    public static void after(JoinPoint joinPoint, ApiOperation apiOperation) {
        System.out.println("方法运行后");
        System.out.println("获取方法上注解名称：" + apiOperation.value());
    }

    //后置异常通知
    @AfterThrowing(value = "execution(* com.yty.demo.service..*.*(..))",
            throwing = "ex")
    public static void afterException(Exception ex) {
        //捕获异常栈信息
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw, true));
    }

    //后置返回通知
    @AfterReturning(value = "execution(* com.yty.demo.service..*.*(..))",
            returning = "returnValue")
    public static void afterEnd(Object returnValue) {
        System.out.println("方法结束，返回值是：" + returnValue);
    }

    //环绕通知
    @Around(value = "pointcut()")
    public Object arround(ProceedingJoinPoint joinPoint) {
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //获取参数
        Object[] args = joinPoint.getArgs();
        Object returnValue = null;
        try {
            System.out.println("前置通知：" + methodName + "方法执行，参数：" + Arrays.asList(args));
            joinPoint.proceed();
            System.out.println("后置通知：" + methodName + "方法执行，参数：" + Arrays.asList(args));
        } catch (Throwable e) {
            log.error("异常通知：", e);
        } finally {
            System.out.println("返回通知：" + returnValue);
        }
        return returnValue;
    }
}
